//引入express模块
const express = require('express');
const cors = require('cors')
//引入数据库连接模块
const pool = require('../pool.js');
//创建路由器对象
const r = express.Router();
//添加路由
const jwt = require('jsonwebtoken');
// const { id } = require('element-plus/es/locale/index.js');
const secret = "secret";
const exp = '1800s';


// 保存cookie
r.post('/savecookie', (req, res, next) => {
    const accountid = req.body.accountid;
    const accountname = req.body.accountname;
    const userId = req.body.userId;
    const cookie = req.body.cookie;
    const mysql1 = `select * from lutian_cookies WHERE accountid = ${accountid} AND userId = ${userId}`
    pool.query(mysql1, (err, r) => {
        if (err) {
            next(err)
            return;
        } else {
            if (r.length > 0) {
                let mysql2 = `UPDATE lutian_cookies SET cookie = '${cookie}' WHERE accountid = ${accountid} AND userId = ${userId};`
                pool.query(mysql2, (err, r) => {
                    if (err) {
                        next(err);
                        return;
                    } else {
                        res.send({ code: 200, msg: "修改cookie成功" });
                    }
                })
            } else {
                let mysql2 = `insert into lutian_cookies set accountid=${accountid},accountname="${accountname}",userId=${userId},cookie="${cookie}"`
                pool.query(mysql2, (err, r) => {
                    if (err) {
                        next(err);
                        return;
                    } else {
                        res.send({ code: 200, msg: "新增cookie成功" });
                    }
                })
            }
        }
    })

})

// 查询cookie
r.get('/saveCookielist', (req, res, next) => {
    let accountid = req.query.accountid;
    let userId = req.query.userId;
    let sqlstr = `select * from lutian_cookies WHERE accountid = ${accountid} AND userId = ${userId}`
    pool.query(sqlstr, (err, r) => {
        if (err) {
            next(err);
            return;
        } else {
            res.send({ code: 200, msg: "查询成功", data: r });
        }
    })
})

// 批量查询cookie
r.get('/saveCookies', (req, res, next) => {
    let accountids = JSON.parse(req.query.accountids);
    let userId = req.query.userId;
    let sqlstr = ''
    accountids.forEach((item, index) => {
        if (index != 0) {
            sqlstr += ` UNION ALL select * from lutian_cookies WHERE accountid = ${item} AND userId = ${userId}`
        } else {
            sqlstr += `select * from lutian_cookies WHERE accountid = ${item} AND userId = ${userId}`
        }
    });
    // let sqlstr = `select * from lutian_cookies WHERE accountid = ${accountid} AND userId = ${userId}`
    pool.query(sqlstr, (err, r) => {
        if (err) {
            next(err);
            return;
        } else {
            res.send({ code: 200, msg: "查询成功", data: r });
        }
    })
})







//暴露出去
module.exports = r;